package com.base.servlet;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.base.utils.DateUtil;

public class FileUploadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * 上传文件最大为100M
	 */
	public int maxSize = 100*1024*1024;
	
	private Logger logger = LoggerFactory.getLogger(FileUploadServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		resp.setContentType("text/html;charset=UTF-8");
		try {
			req.setCharacterEncoding("UTF-8");
		} catch(UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			logger.error("set encoding error!" + e.getMessage());
		}
		String resolvePath = "/files/" + DateUtil.formatDateToString(new Date(), "yyyyMMdd");
		String dirPath = req.getSession().getServletContext().getRealPath("/") + resolvePath;
		File file = new File(dirPath);
		if(!file.exists() || !file.isDirectory())
			file.mkdirs();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(4096);
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(maxSize);
		String resultStr = "";
		try {
			List<FileItem> fileItems = upload.parseRequest(req);
			Iterator<FileItem> iterator = fileItems.iterator();
			while(iterator.hasNext()) {
				FileItem item = iterator.next();
				if (!item.isFormField()) {
					//随机生成新的文件名
					String newName = "/" + UUID.randomUUID();
					try {
						item.write(new File(dirPath + newName));
						resultStr = resolvePath + newName;
					} catch (Exception e) {
						// TODO Auto-generated catch block
						logger.error("write file error!" + e.getMessage());
					}
				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			logger.error("file upload error!" + e.getMessage());
		}
		
		resp.getWriter().print(resultStr);
	}

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		String ms = getInitParameter("maxSize");
		if(ms != null){
			String[] s = ms.split("\\*");
			int value = 1;
			for(int i = 0;i < s.length;i++){
				value = value * Integer.valueOf(StringUtils.trim(s[i]));
			}
			maxSize = Integer.valueOf(value);
		}
	}
}
